package net.yunxinyong.sign.controller;

import lombok.extern.slf4j.Slf4j;
import net.yunxinyong.sign.entity.SignAdmin;
import net.yunxinyong.sign.mapper.SignAdminMapper;
import net.yunxinyong.sign.service.AdminService;
import net.yunxinyong.sign.service.RedisService;
import net.yunxinyong.sign.service.VerificationCodeService;
import net.yunxinyong.sign.utils.CECResultUtil;
import net.yunxinyong.sign.utils.FTPUtils;
import net.yunxinyong.sign.vo.LoginVo;
import net.yunxinyong.sign.vo.ResponseVo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

/**
 *@describe  登录相关
 *@author  ttbf
 *@date  2018/10/24
 */
@Slf4j
@RestController
@RequestMapping(value = "passport")
public class PassPortController {


    @Autowired
    private AdminService loginAdminService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private SignAdminMapper signAdminMapper;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResponseVo login(@RequestBody LoginVo loginVo, HttpServletRequest request,
                            HttpServletResponse response) {


        UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getPhone(), loginVo.getPassword(), true);
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
        try {
            // 在调用了login方法后,SecurityManager会收到AuthenticationToken,并将其发送给已配置的Realm执行必须的认证检查
            // 每个Realm都能在必要时对提交的AuthenticationTokens作出反应
            // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            currentUser.login(token);
            Object principals = SecurityUtils.getSubject().getPrincipals();
            String role = null;
            if (principals != null){
                Integer adminId = (Integer) SecurityUtils.getSubject().getPrincipal();
                SignAdmin adminById = loginAdminService.getAdminById(adminId);
                adminById.setPassword(null);
                adminById.setHash(null);
                return CECResultUtil.success("登录成功！",adminById);
            }else {
                return CECResultUtil.error("请登录！");
            }


        } catch (Exception e) {
            log.error("登录失败，用户名[{}]", loginVo.getPhone(), e);
            token.clear();
            return CECResultUtil.error(e.getMessage());
        }
    }



    /**
     * 退出登陆接口
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public void logout() {
    }

    /**
     * 判断是否登陆接口
     */
    @RequestMapping(value = "/islogin", method = RequestMethod.GET)
    public ResponseVo isLogin() {
        Object principals = SecurityUtils.getSubject().getPrincipals();
        if (principals != null) {
            return CECResultUtil.success("已登陆");
        } else {
            return CECResultUtil.error("未登录");
        }
    }

    @RequestMapping(value = "/file",method = RequestMethod.POST)
    public ResponseVo file(MultipartFile file, HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        if (file == null){

            return CECResultUtil.error("请选择文件");
        }
        file.getSize();
        String fileName = new Date().getTime() + file.getOriginalFilename();
        boolean b = FTPUtils.uploadFile(fileName, file.getInputStream());


        return CECResultUtil.success("文件上传成功",fileName);

    }

    @RequestMapping(value = "/getfile",method = RequestMethod.GET)
    public ResponseVo getfile(String filename, HttpServletRequest request,
                               HttpServletResponse response) throws IOException {
        String userAgent = request.getHeader("User-Agent");
        InputStream inputStream = FTPUtils.getInputStream(filename);
        int available = inputStream.available();
        /* 第三步：创建缓冲区，大小为流的最大字符数 */
        byte[] buffer = new byte[available]; // int available() 返回值为流中尚未读取的字节的数量
        /* 第四步：从文件输入流读字节流到缓冲区 */
        inputStream.read(buffer);
        /* 第五步： 关闭输入流 */

        inputStream.close();

        byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8");
        response.reset();
        response.setCharacterEncoding("utf-8");
        response.addHeader("Content-Disposition",
                "attachment;filename=" + new String(bytes, "iso8859-1"));
        response.addHeader("Content-Length", "" + available);
        /* 第六步：创建文件输出流 */
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream; charset=utf-8");
        /* 第七步：把缓冲区的内容写入文件输出流 */
        outputStream.write(buffer);
        /* 第八步：刷空输出流，并输出所有被缓存的字节 */
        outputStream.flush();
        /* 第九步：关闭输出流 */
        outputStream.close();

        return CECResultUtil.success("文件获取成功");

    }
}
